package com.example.shop.rabbitmq.component;

import org.springframework.amqp.core.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;

@Configuration
public class GoodsComponent {
    /**
     * 商品交换机名
     */
    public static final String GOODS_EXCHANGE = "goods.direct";
    /**
     * 库存检测的路由键
     */
    public static final String INVENTORY_DETECT_ROUTING_KEY = "GoodsInventoryDetect";
    /**
     * 库存检测队列
     */
    public static final String INVENTORY_DETECT_QUEUE = "goods.detect.inventory.queue";


    /**
     * 声明一个商品的交换机
     * @return 返回一个Direct路由交换机
     */
    @Bean
    public DirectExchange goodsExchange(){
        //声明一个Direct路由交换机，交换机名为GOODS_EXCHANGE
        return ExchangeBuilder.directExchange(GOODS_EXCHANGE)
                //设置该交换机的持久性配置参数为持久化
                .durable(true)
                .build();
    }

    /**
     * 声明一个库存检测队列
     * @return 返回一个库存检测队列
     */
    @Bean
    public Queue goodsInventoryDetectQueue(){
        HashMap<String, Object> queueProperties = new HashMap<>();
        queueProperties.put("x-overflow","reject-publish-dlx");
        queueProperties.put("x-queue-mode", "lazy");
        //durable:持久化(true),exclusive：消费者不独占队列(true),autoDelete:不自动删除队列(false),arguments:队列配置参数(queueProperties)
        return new Queue(INVENTORY_DETECT_QUEUE,true,false,false,queueProperties);
    }

    /**
     * 将商品的交换机和库存检测队列绑定在一起，绑定的键名为INVENTORY_DETECT_QUEUE
     * @param goodsExchange 商品的交换机
     * @param goodsInventoryDetectQueue 库存检测队列
     * @return 返回绑定对象Binding
     */
    @Bean
    public Binding inventoryDetectBinding(DirectExchange goodsExchange, Queue goodsInventoryDetectQueue){
        return BindingBuilder.bind(goodsInventoryDetectQueue).to(goodsExchange).with(INVENTORY_DETECT_QUEUE);
    }

}
